package com.loyalove.zerone.boot.base;


import com.loyalove.zerone.boot.common.utils.ValidatorUtil;
import com.loyalove.zerone.common.entity.Result;
import com.loyalove.zerone.common.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * Base控制器
 *
 * @author loyal
 */
@ControllerAdvice
@Slf4j
public class ExceptionControllerAdvice {

  /**
   * 参数绑定异常
   *
   * @author loyalove
   */
  @ExceptionHandler(BindException.class)
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  @ResponseBody
  public Result bindError(BindException e) {
    String validateMsg = ValidatorUtil.getValidateMsg(e);
    log.error("请求参数异常", e.getMessage());
    return Result.error(validateMsg);
  }

  /**
   * 拦截业务异常
   *
   * @author loyalove
   */
  @ExceptionHandler(BizException.class)
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  @ResponseBody
  public Result notFount(BizException e) {
    log.trace("业务异常{}", e);
    return Result.error(e.getMessage());
  }

  /**
   * 拦截未知的运行时异常
   *
   * @author loyalove
   */
  @ExceptionHandler(RuntimeException.class)
  @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  @ResponseBody
  public Result notFount(RuntimeException e) {
    log.error("运行时异常", e.getMessage());
    return Result.error(e.getMessage());
  }


}
